package com.yuanrui.yrclub.oss.utils;

import com.aliyun.oss.OSS;
import com.yuanrui.yrclub.oss.entity.FileInfo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 阿里云工具类
 */
@Component
public class AliUtil {

    @Resource
    private OSS ossClient;


    /**
     * 创建bucket
     *
     * @param bucket bucket名称
     */
    public void createBucket(String bucket) {
        // 创建bucket
        boolean exist = ossClient.doesBucketExist(bucket);
        if (!exist) {
            ossClient.createBucket(bucket);
        }
    }

    /**
     * 上传文件
     */
    public void uploadFile(InputStream inputStream, String bucket, String objectName) throws Exception {
        ossClient.putObject(bucket, objectName, inputStream);
    }

    /**
     * 列出所有桶
     */
    public List<String> getAllBucket() throws Exception {
        List<com.aliyun.oss.model.Bucket> buckets = ossClient.listBuckets();
        return buckets.stream().map(com.aliyun.oss.model.Bucket::getName).collect(Collectors.toList());
    }


    /**
     * 列出当前桶及文件
     */
    public List<FileInfo> getAllFile(String bucket) throws Exception {
        List<com.aliyun.oss.model.Bucket> buckets = ossClient.listBuckets();
        List<FileInfo> fileInfoList = new LinkedList<>();
        for (com.aliyun.oss.model.Bucket bucket1 : buckets) {
            List<com.aliyun.oss.model.OSSObjectSummary> objectSummaries = ossClient.listObjects(bucket1.getName()).getObjectSummaries();
            for (com.aliyun.oss.model.OSSObjectSummary objectSummary : objectSummaries) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setFileName(objectSummary.getKey());
                fileInfo.setDirectoryFlag(objectSummary.getKey().endsWith("/"));
                fileInfo.setEtag(objectSummary.getETag());
                fileInfoList.add(fileInfo);
            }
        }
        return fileInfoList;
    }

    /**
     * 下载文件
     */
    public InputStream downLoad(String bucket, String objectName) throws Exception {
        return ossClient.getObject(bucket, objectName).getObjectContent();
    }

    /**
     * 删除桶
     */
    public void deleteBucket(String bucket) throws Exception {
        ossClient.deleteBucket(bucket);
    }

    /**
     * 删除文件
     */
    public void deleteObject(String bucket, String objectName) throws Exception {
        ossClient.deleteObject(bucket, objectName);
    }

    /**
     * 获取url
     */
    public String getUrl(String bucket, String objectName) {
        // 设置URL过期时间为不限时
        URL url = ossClient.generatePresignedUrl(bucket, objectName, new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365));
        return url.toString();
    }
}
